package com.heima.a07_demo.server.service.impl;


import com.heima.a07_demo.common.exception.CommonException;
import com.heima.a07_demo.common.exception.PasswordErrorException;
import com.heima.a07_demo.pojo.dto.DoctorLoginCodeDTO;
import com.heima.a07_demo.pojo.dto.DoctorLoginDTO;
import com.heima.a07_demo.pojo.entity.Doctor;
import com.heima.a07_demo.server.mapper.LoginMapper;
import com.heima.a07_demo.server.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.heima.a07_demo.common.exception.AccountNotFoundException;
import org.springframework.util.DigestUtils;

/*
*
* 登陆
* */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Doctor login(DoctorLoginDTO doctorLoginDTO) {
        String phoneNumber = doctorLoginDTO.getPhoneNumber();
        String password = doctorLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Doctor doctor =loginMapper.getByPhoneNumber(phoneNumber) ;

        //2、处理各种异常情况（用户名不存在、密码不对）
        if (doctor == null) {
            //账号不存在
            System.out.println("账号不存在");
            throw new AccountNotFoundException("账号不存在");
        }

        //密码比对
        password= DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("加密后的密码:{}",password);
        //System.out.println(password);
        if (!password.equals(doctor.getPassword())) {
            //密码错误
            System.out.println("密码错误");
            throw new PasswordErrorException("密码错误");
        }
        //3、返回实体对象
        return doctor;
    }

    @Override
    public Doctor loginByCode(DoctorLoginCodeDTO doctorLoginCodeDTO) {
        String phoneNumber = doctorLoginCodeDTO.getPhoneNumber();
        String code = doctorLoginCodeDTO.getCode();

        //1、根据用户名查询数据库中的数据
        Doctor doctor =loginMapper.getByPhoneNumber(phoneNumber) ;

        //2、处理各种异常情况（用户名不存在、密码不对）
        if (doctor == null) {
            //账号不存在
            System.out.println("账号不存在");
            throw new AccountNotFoundException("账号不存在");
        }
        //获取验证码
        String key="A07:login:code:"+phoneNumber;
        String cacheCode=stringRedisTemplate.opsForValue().get(key);
        log.info("输入的验证码是：{},正确的验证码是: {}",code,cacheCode);
        if(cacheCode==null||!code.equals(cacheCode)){
            System.out.println("验证码错误");
            throw new CommonException("验证码错误");
        }
        //3、返回实体对象
        return doctor;
    }
}
